<template>
  <div>
    <el-button @click="handleVis" type="primary" icon="el-icon-plus"
      >添加</el-button
    >
    <el-table :data="cords" border style="width: 100%; margin-top: 20px">
      <el-table-column type="index" label="序号" align="center" width="180">
      </el-table-column>
      <el-table-column
        prop="tmName"
        label="品牌名称"
        align="center"
        width="180"
      >
      </el-table-column>
      <el-table-column align="center" label="品牌LOGO">
        <template slot-scope="{ row }">
          <img :src="row.logoUrl" alt="" style="width: 50px; height: 50px" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button
            icon="el-icon-edit"
            size="mini"
            type="warning"
            @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button
            icon="delete"
            size="mini"
            type="danger"
            @click="open(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :total="tradeList.total"
      style="margin-top: 20px; textalign: center"
      :current-page="tradeList.current"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
      :page-size="tradeList.size"
      :page-sizes="[3, 5, 7]"
      layout="prev, pager, next, jumper,-> ,sizes, total"
    >
    </el-pagination>
    <el-dialog
      :title="form.id ? '修改品牌' : '添加品牌'"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <!-- :before-close="handleClose" -->
      <el-form
        :rules="rules"
        ref="form"
        :model="form"
        style="width: 93%"
        label-width="120px"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="form.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌Logo">
          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.logoUrl" :src="form.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addTrade">确 定</el-button>
      </span>
    </el-dialog>
    <el-button type="danger" @click="Mdelete">清除行动！</el-button>
    <el-button type="danger" @click="shiyan">试一试</el-button>
  </div>
</template>

<script>
import {
  reqAddOrUpdateTradeMark,
  reqDeleteTradeMark,
  reqTradeMarkList,
} from "@/api/tradeMark";
import { mapState } from "vuex";
export default {
  name: "TradeMark",
  data() {
    return {
      a:'',
      limit: 5,
      page: 1,
      dialogVisible: false,
      // 数据收集
      form: {
        tmName: "",
        logoUrl: "",
      },
      rules: {
        tmName: [
          {
            required: true,
            message: "请输入品牌名称！",
            trigger: "blur",
          },
          { pattern: /^.{2,7}$/, message: "长度为2~7", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    shiyan() {
      console.log(this.a);
    },
    tradeData() {
      this.$store.dispatch("tradeMark/getTradeList", {
        page: this.page,
        limit: this.limit,
      });
    },
    handleCurrentChange(page) {
      this.page = page;
      this.tradeData();
    },
    handleSizeChange(limit) {
      this.limit = limit;
      this.tradeData();
    },
    // 编辑
    handleEdit(row) {
      this.dialogVisible = true;
      this.form = { ...row };
      // console.log(this.tradeList);
    },

    // upload函数
    handleAvatarSuccess(res, file) {
      // console.log(res);
      this.form.logoUrl = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 确定按钮，添加品牌
    addTrade() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.dialogVisible = false;
          // console.log(this.form);
          let result = await reqAddOrUpdateTradeMark(this.form);
          // console.log(result.code);
          if (result.code == 200) {
            this.$message({
              message: !this.form.id ? "添加成功" : "修改成功",
              type: "success",
            });
            // 如果是添加品牌page为第一页，如果是修改品牌，page应停留在该页。
            let pagea = this.page;
            this.page = this.form.id ? pagea : 1;
            this.tradeData();
          }
        } else {
          return false;
        }
      });
    },

    handleVis() {
      this.dialogVisible = true;
      this.form = {
        tmName: "",
        logoUrl: "",
      };
    },
    // messageBox   删除商品提示框
    open(id) {
      this.$confirm("是否删除商品？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let result = await reqDeleteTradeMark(id);
          if (result.code == 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.page =
              this.cords.length > 1 || this.page == 1
                ? this.page
                : this.page - 1;
            this.tradeData();
          } else {
            this.$message({
              type: "danger",
              message: "删除失败!",
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async Mdelete() {
      // console.log(this.cords);
      let result1 = await reqTradeMarkList(3, 30);
      let a = result1.data.records;
      console.log(a);
      setInterval(() => {
        a.forEach(async (p) => {
          let result2 = await reqDeleteTradeMark(p.id);
          if (result2.code == 200) {
            console.log("成功");
          }
        });
      }, 3000);
    },
  },
  computed: {
    ...mapState("tradeMark", ["tradeList"]),
    cords() {
      return this.tradeList.records;
    },
  },
  mounted() {
    this.tradeData();
    this.a = 1;
  },
};
</script>

<style lang='less'>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>